package com.ztstkj.lzscale.adpters

import android.annotation.SuppressLint
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.sscl.baselibrary.utils.DebugUtil
import com.ztstkj.lzscale.R

class OptionAdapter(private var datas: List<OptionItem>) :
    RecyclerView.Adapter<OptionAdapter.ItemViewHolder>() {
    private lateinit var context: Context
    private var selectedPoisiton: Int = RecyclerView.NO_POSITION
    var selectedValue: Int = 0
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder {
        context = parent.context
        val v = LayoutInflater.from(parent.context)
            .inflate(R.layout.setting_option, parent, false)
        return ItemViewHolder(v)
    }

    @SuppressLint("UseCompatLoadingForDrawables", "NotifyDataSetChanged")
    override fun onBindViewHolder(holder: ItemViewHolder, @SuppressLint("RecyclerView") position: Int) {
        val bean = datas[position]
        holder.optionName.setTextColor(context.getColor(R.color.setting_center_unselect_color))
        holder.optionName.background = context.getDrawable(R.drawable.setting_center_unselect_bg)
        holder.optionName.text = bean.name

        holder.onSelect(position == selectedPoisiton)
        holder.optionName.setOnClickListener {
            selectedPoisiton = position
            selectedValue=datas[position].value
            notifyDataSetChanged()
        }
    }
    @SuppressLint("NotifyDataSetChanged")
    fun setValue(value:Int){
        selectedValue=value
        selectedPoisiton=datas.indexOfFirst { it.value==value }
        DebugUtil.debugOut("回显： ${value}，${selectedPoisiton}" )
        notifyDataSetChanged()
    }

    override fun getItemCount(): Int {
        return datas.size
    }

    inner class ItemViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val optionName: TextView = view.findViewById(R.id.tvOptionId)
        @SuppressLint("UseCompatLoadingForDrawables")
        fun onSelect(isSelected: Boolean) {
            if (isSelected) {
                optionName.setTextColor(context.getColor(R.color.setting_center_selected_color))
                optionName.background = context.getDrawable(R.drawable.setting_center_selected)
            } else {
                optionName.setTextColor(context.getColor(R.color.setting_center_unselect_color))
                optionName.background = context.getDrawable(R.drawable.setting_center_unselect_bg)
            }
        }
    }
}